package com.jlnk.androidfmc;

import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.jlnk.androidfmc.R;
import com.jlnk.androidfmc.database.ProductDatabaseHelper;
import com.jlnk.androidfmc.fragment.BuyerFragment;
import com.jlnk.androidfmc.fragment.ConsultFragment;
import com.jlnk.androidfmc.fragment.SellerFragment;
import com.jlnk.androidfmc.fragment.fragments.FarmerCircleFragment;
import com.jlnk.androidfmc.fragment.fragments.MessageFragment;
import com.jlnk.androidfmc.presenter.MainPresenter;
import com.jlnk.androidfmc.presenter.MainPresenterImpl;
import com.jlnk.androidfmc.view.MainView;

public class MainActivity extends AppCompatActivity implements MainView, View.OnClickListener {
    private static final int YOUR_REQUEST_CODE = 1;
    private FrameLayout fragmentContainer;
    private Button btnToggle;
    private MainPresenter presenter;
    private boolean isHomeFragmentDisplayed = true;
    private SellerFragment sellerFragment;
    private BuyerFragment buyerFragment;
    private ProductDatabaseHelper databaseHelper; // 添加数据库帮助类成员变量
    public static String consultationInfo;
    private String param1;

    private String param2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        fragmentContainer = findViewById(R.id.fragment_container);
        btnToggle = findViewById(R.id.btn_toggle);

        sellerFragment = new SellerFragment();
        buyerFragment = new BuyerFragment();

        // 初始化并添加 ConsultFragment 和 MessageFragment
        addFragments();


        // 初始化数据库帮助类
        databaseHelper = new ProductDatabaseHelper(this); // 初始化数据库帮助类

        // 确保数据库和表被创建
        try {
            SQLiteDatabase db = databaseHelper.getReadableDatabase();
            // 尝试查询 categories 表，如果表不存在，将会抛出 SQLiteException
            db.rawQuery("SELECT * FROM " + ProductDatabaseHelper.TABLE_CATEGORIES + " LIMIT 1", null).close();
        } catch (SQLiteException e) {
            e.printStackTrace();
            // 可以在这里处理异常，例如显示一个错误消息
        }

        // 打开数据库连接
        SQLiteDatabase db = databaseHelper.getWritableDatabase(); // 打开数据库连接
        db.close(); // 关闭数据库连接

        // Initialize presenter
        presenter = new MainPresenterImpl(this, sellerFragment, buyerFragment);

        // Initialize interface display
        displayFragment(buyerFragment);
        setToggleText("去卖货");
        setOnClickListener(btnToggle);
        setGoSellVisibility(false);
    }

    private void addFragments() {
        // 添加 ConsultFragment
        ConsultFragment consultFragment = new ConsultFragment();
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.add(R.id.fragment_container, consultFragment, "ConsultFragmentTag");
        fragmentTransaction.commit();

        // 添加 MessageFragment
        MessageFragment messageFragment = new MessageFragment();
        fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.add(R.id.fragment_container, messageFragment, "MessageFragmentTag");
        fragmentTransaction.commit();

        // 假设这是MainActivity中的代码
        FragmentManager fragmentManager = getSupportFragmentManager();
        FarmerCircleFragment newFragment = FarmerCircleFragment.newInstance(param1, param2);
        fragmentManager.beginTransaction()
                .replace(R.id.fragment_container, newFragment).commit();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    // MainView Interface Methods
    @Override
    public void displayFragment(Fragment fragment) {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(fragmentContainer.getId(), fragment);
        fragmentTransaction.commit();

        getSupportFragmentManager().beginTransaction()
                .replace(R.id.fragment_container, fragment)
                .commit();


    }

    @Override
    public void setToggleText(String text) {
        btnToggle.setText(text);
    }

    @Override
    public void setOnClickListener(Button button) {
        button.setOnClickListener(this);
    }

    // View.OnClickListener Implementation
    @Override
    public void onClick(View v) {
        if (v.getId() == btnToggle.getId()) {
            presenter.onToggleClick();
        }
    }

    public void setGoSellVisibility(boolean isVisible) {
        LinearLayout linearGoSell = findViewById(R.id.linear_goSell);
        if (linearGoSell != null) {
            linearGoSell.setVisibility(isVisible ? View.VISIBLE : View.GONE);
        }
    }

    // MainActivity.java
// MainActivity.java
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == YOUR_REQUEST_CODE && resultCode == RESULT_OK) {
            if (data != null) {
                String consultationContent = data.getStringExtra("CONSULTATION_CONTENT");
                MessageFragment messageFragment = findMessageFragment();
                if (messageFragment != null) {
                    messageFragment.updateConsultationInfo("专家姓名", consultationContent);
                }
            }
        }
    }

    // 辅助方法，用于在 MainActivity 中找到 MessageFragment 实例
// MainActivity.java
    private MessageFragment findFragmentWithTag(String tag) {
        Fragment fragment = getSupportFragmentManager().findFragmentByTag(tag);
        return fragment instanceof MessageFragment ? (MessageFragment) fragment : null;
    }
    // MainActivity.java

    public void displayConsultationInfo(String expertName, String consultationContent) {
        // 使用 tag 来找到 MessageFragment
        MessageFragment messageFragment = findFragmentWithTag("MessageFragmentTag");
        if (messageFragment != null) {
            messageFragment.updateConsultationInfo(expertName, consultationContent);
        }
    }

    private MessageFragment findMessageFragment() {
        // 使用 FragmentManager 通过标签查找 MessageFragment
        return (MessageFragment) getSupportFragmentManager().findFragmentByTag("MessageFragmentTag");
    }





}
